package cn.hackcloud.mutithread.juc;

/**
 * volatile是java虚拟机提供的轻量级的同步机制
 * 1.保证可见性
 * 2.不保证原子性
 * 3.禁止重排序
 *
 * Java内存模型同步的规定
 * 1.线程解锁前、必须把共享变量的值刷新回主内存
 * 2.线程加锁前、必须读取主内存的最新值到自己的工作内存
 * 3.加锁解锁是同一把锁
 */
public class TestVolatile {
	public static void main(String[] args) {
		VolatileDemo demo = new VolatileDemo();
		new Thread(demo).start();
		while (true) {
			synchronized (demo) {
				if (demo.isFlag()) {
					System.out.println("------------------");
					break;
				}
			}
		}
	}
}

class VolatileDemo implements Runnable {
	private volatile boolean flag = false;

	@Override
	public void run() {
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		flag = true;
		System.out.println("flag:" + flag);

	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

}
